<template>
    <div class="gd-main">
        <!-- 发起合同表单 -->
        <el-form 
            style="margin-top:0;"
            :rules="rules"
            ref="form" 
            :model="form" 
            label-position="left"
            label-width="120px">
            <el-row type="flex" :gutter="20">
                <!-- 项目名称下拉框 -->
                <el-col :span="10">
                    <el-form-item prop="projectId" label="项目名称" style="margin-bottom:20px !important;">
                        <el-select style="width:100%" v-model="form.projectId" placeholder="选择项目">
                            <el-option 
                                v-for="option in projectOptions"
                                :key="option.projectId"
                                :label="option.projectName" 
                                :value="option.projectId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <!-- 班组长下拉框 -->
                <el-col :span="10">
                    <el-form-item prop="companyId" label="班组长" style="margin-bottom:20px !important;">
                        <el-select 
                            style="width:100%" 
                            v-model="form.companyId" 
                            placeholder="请搜索班组长"
                            :filterable="true"
                            :remote="true"
                            :remote-method="remoteMethod"
                            :loading="loading"
                            :disabled="teamDisabled"
                        >
                            <el-option 
                                v-for="option in subcontractorOptions" 
                                :key="option.subcontractorId"
                                :label="option.subcontractorName" 
                                :value="option.subcontractorId">
                                {{option.subcontractorName}} - {{option.contractPhone}} - <span :style="option.contractStatus | verify">{{option.contractStatus}}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row type="flex" :gutter="20">
                <!-- 合同上传 -->
                <el-col :span="10">
                    <el-form-item label="合同文件">
                        <el-upload
                            :action="uploadUrl" 
                            :http-request="httprequestContract"
                            :before-upload="beforeuploadContract">
                            <el-button :loading="btnOneLoading" type="primary">上传文件</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <!-- 附件上传 -->
                <el-col :span="10">
                    <el-form-item label="附件(非必填)">
                        <el-upload
                            :action="uploadUrl"
                            :http-request="httprequestAttach">
                            <el-button :loading="btnTwoLoading" type="primary">上传文件</el-button>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- 发起签署 -->
            <el-col :span="5">
                <el-button style="width:100%;margin-left:100px;" type="primary" @click="onSubmit('form')">发起签署</el-button>
            </el-col>
        </el-form>
        <!-- 子路由 -->
        <set-signarea v-if="showSignarea" @getarea="getarea"  @hidepdf="hidepdf" :pdffile="file64Str"></set-signarea>
    </div>
</template>

<script>
    // 登录后的可用信息
    import {mapGetters} from 'vuex';
    import setSignarea from '@/views/contract/team/startContract/setSignedArea';
    //引入 ajax 请求的方法
    import {queryProjectInfoByAccount,querySubcontractorList,uploadContractFile,addContract} from '@/request/team';
    import request from '@/utils/request';
    //文件上传路径
    import API from '@/api/contract/team';
    
    export default {
        components:{
          setSignarea  
        },
        computed:{
            //登录后的数据在这里进行给实例赋值，就可以用 this.xxx 进行访问了
          ...mapGetters(['userId','currId','roleId','verificationStatus'])  
        },
        data() {
            return {
                showSignarea:false,
                btnOneLoading:false,
                btnTwoLoading:false,
                //文件上传领
                uploadUrl:API.uploadContractFile,
                //上传的 合同 base64
                file64Str:'',
                teamDisabled:true,
                //表单数据 - 项目名称
                form:{
                    projectId: '',
                    companyId: '',
                    //合同源文件 路径
                    contractSourceFileUrl:'',
                    //附件 路径数组
                    contractEnclosures:[],
                    //签署区页码
                    signatureAreaPage:1,
                    //甲方签署区X轴坐标
                    signatureAreaPartyAX:0,
                    //甲方签署区Y轴坐标
                    signatureAreaPartyAY:0,
                    //甲方签署区Y轴坐标
                    signatureAreaPartyAWidth:0,
                    //甲方签署区高度
                    signatureAreaPartyAHeight:0,
                    //乙方签署区X轴坐标
                    signatureAreaPartyBX:0,
                    //乙方签署区Y轴坐标
                    signatureAreaPartyBY:0,
                    //乙方签署区宽度
                    signatureAreaPartyBWidth:0,
                    //乙方签署区高度
                    signatureAreaPartyBHeight:0
                },
                projectOptions: [],
                subcontractorOptions: [],
                //表单验证规则 [ 也可以自己配置验证规则 ]
                rules:{
                    projectId:[{required:true,message:'请选择项目',trigger:'change'}],
                    //项目状态验证
                    companyId:[{required:true,message:'请先选择项目再选择班组长',trigger:'change'}]
                },
                //下拉框搜索是的状态
                loading:false,
                searchCid:null
            }
        },
        filters:{
          verify(val){
              switch(val){
                  case '未认证':
                    return 'color:orange';
                  case '已认证':
                    return 'color:green'
              }
          }
        },
        watch:{
            'form.projectId':{
                deep:true,
                handler(val){
                    //如果为选择项目，班组长搜索禁用
                    if(val == ''){
                        this.teamDisabled = true;
                    }else{
                        this.teamDisabled = false;
                        //进行班组长查询执行一次
                        this.remoteMethod('');
                    }
                }
            }
        },
        methods:{
            //隐藏pdf
            hidepdf(){
                this.showSignarea = false;
            },
            getarea(value){
                this.showSignarea = false;
                Object.assign(this.form,value);
                console.log(this.form);
                this.addContract(this.form);
            },
            //提交表单
            onSubmit(formRef){
                this.$refs[formRef].validate((valid) => {
                    //验证通过
                    if(valid){
                        console.log('表单项验证通过');
                        if(this.form.contractSourceFileUrl == ''){
                            this.$message({
                                type:'warning',
                                message:'请上传合同文件'
                            });
                            return;
                        }
                        
                        if(this.btnOneLoading == true){
                            this.$message({
                                type:'warning',
                                message:'文件正在上传中'
                            });
                            return;
                        }
                        this.showSignarea = true;
                    }
                });
            },
            //文件上传前调用
            beforeuploadContract(file){
                console.log(file.type);
                if(file.type.indexOf('pdf') == -1){
                    this.$message({
                        type:'error',
                        message:'请上传 pdf 文件'
                    });
                    return false;
                }
            },
            //合同 - 上传
            httprequestContract(param){
                let file = param.file,
                    reader = new FileReader();
                this.btnOneLoading = true;
                reader.readAsDataURL(file);
                reader.onload = () => {
                    request(param.action,{
                        method:'post',
                        data:{
                            fileName:file.name,
                            fileBase64:reader.result
                        },
                        timeout:0
                    //存储文件上传的路径
                    }).then(res => {
                        this.form.contractSourceFileUrl = res.data.fileUrl;
                        this.btnOneLoading = false;
                        this.file64Str = reader.result;
                        console.log('合同的文件路径: ',this.form.contractSourceFileUrl);
                    }).catch(() => {
                        this.btnOneLoading = false;
                    });
                }
            },
            //附件 - 上传
            httprequestAttach(param){
                let file = param.file,
                    reader = new FileReader();
                this.btnTwoLoading = true;
                reader.readAsDataURL(file);
                reader.onload = () => {
                    request(param.action,{
                        method:'post',
                        data:{
                            fileName:file.name,
                            fileBase64:reader.result
                        },
                        timeout:0
                    //存储 - 附件路径
                    }).then(res => {
                        this.form.contractEnclosures.push(res.data.fileUrl);
                        this.btnTwoLoading = false;
                        console.log('合同的文件路径: ',this.form.contractEnclosures);
                    }).catch(() => {
                        this.btnTwoLoading = false;
                    });
                }
            },
            //提交合同
            addContract(queryObj){
                let params = {
                    userId:this.userId,
                    currId:this.currId,
                    roleId:this.roleId,
                    contractType:1
                }
                Object.assign(params,queryObj);
                
                params.contractEnclosures = JSON.stringify(params.contractEnclosures);
                
                return addContract(params).then(res => {
                    console.log('合同上传',res);
                    this.$message({
                        message:res.msg,
                        type:'success'
                    });
                    //关闭弹窗
                    this.showSignarea = false;
                });
            },
            //班组长查询 -  需要节流处理
            remoteMethod(val){
                this.loading = true;
                clearTimeout(this.searchCid);
                this.searchCid = setTimeout(() => {
                   this.querySubcontractorList({
                       name:val,
                       projectId:this.form.projectId
                   }).then(res => {
                        this.loading = false;
                    }).catch(() => {
                        this.loading = false;
                    }); 
                },2000);
            },
            //班组长查询
            querySubcontractorList(queryObj){
                let params = {
                      userId:this.userId,
                      currId:this.currId,
                      roleId:this.roleId
                };
                Object.assign(params,queryObj);
                return querySubcontractorList(params).then(res => {
                   console.log('班组长查询',res);
                   this.subcontractorOptions = res.data || [];
                });
            },
            //查询项目
            queryProjectInfoByAccount(queryObj){
                let params = {
                    userId:this.userId,
                    currId:this.currId,
                    roleId:this.roleId  
                };
                
                Object.assign(params,queryObj);
                
                return queryProjectInfoByAccount(params).then(res => {
                   console.log('查询项目',res);
                   this.projectOptions = res.data || [];
                });
            }
        },
        mounted(){
            this.queryProjectInfoByAccount();
        }
    }
</script>